package com.xy.yunduo.config;


import com.xy.yunduo.utils.response.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalDefultExceptionHandler {
    private final Logger log= LoggerFactory.getLogger(GlobalDefultExceptionHandler.class);

    @Autowired
    private MessageSource messageSource;

    //声明要捕获的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public <T> ApiResponse<T> defultExcepitonHandler(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        if(e instanceof ApiException) {
            log.error("业务异常："+e.getMessage());
            ApiException apiException = (ApiException)e;
            ErrorCode code=new ErrorCode(apiException.getCode(), MessageHolder.get(apiException.getMessage()));
            return ServerResponseUtil.replyError(code);
        }else{
            log.error("系统异常："+e.getMessage(),e);
            return ServerResponseUtil.replyError(CommonErrorCodes.SYSTEM_ERROR);
        }
    }
}
